/**
 *       Copyright (c) 2011 Lukas Zaruba
 * 
 *   This file is part of ParPortTester
 *
 *   ParPortTester is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Lesser General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   ParPortTester is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public License
 *   along with ParPortTester. If not, see <http://www.gnu.org/licenses/>.
 */


package net.zarubsys.parporttester.utils;

import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author  &lt;A HREF=&quot;mailto:lukas.zaruba@gmail.com&quot;&gt;Lukas Zaruba&lt;/A&gt; zarubsys.net
 */
public class IOHWUtils {
	
	private int[] addresses;
	private String[] names;
	
	private static final Logger LOG = Logger.getLogger(IOHWUtils.class.getName());
	
	private static final IOHWUtils INSTANCE = new IOHWUtils();
	
	private IOHWUtils() {
		// to prevent instantiation
		init();
	}
	
	public static IOHWUtils getInstance() {
		return INSTANCE;
	}

	private void init() {
		String addrs = System.getProperty("portAddresses", "378"); //$NON-NLS-1$ //$NON-NLS-2$
		String[] rawAddresses = addrs.split(","); //$NON-NLS-1$
		addresses = new int[rawAddresses.length];
		int i = 0;
		for (String address : rawAddresses) {
			try {
				addresses[i] = Integer.parseInt(address, 16);
			} catch (Exception e) {
				LOG.log(Level.SEVERE, "Cannot parse address!", e); //$NON-NLS-1$
				throw new IllegalArgumentException(e);
			}
			i++;
		}
		
		String rawNames = System.getProperty("portNames", "LPT1"); //$NON-NLS-1$ //$NON-NLS-2$
		this.names = rawNames.split(","); //$NON-NLS-1$
	}
	
	public String[] getPortNames() {
		String[] values = Arrays.copyOf(names, names.length);
		return values;
	}
	
	public int getPortAddress(int offset) {
		return addresses[offset];
	}
	
	public int addOffset(int base, int byteIndex) {
		return base + byteIndex;
	}

}
